package shopaddmin;

//import resources.JDialog_AddItemToStore;
import digitshoplogic.DBAccessSingleton;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import shopaddmin.JDialog_AddItemToStore;
import shopaddmin.ShopAddminApp;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * IventoryJPanel.java
 *
 * Created on 24-Apr-2011, 11:01:49 PM
 */

/**
 *
 * @author james
 */
public class IventoryJPanel extends javax.swing.JPanel {

    /** Creates new form IventoryJPanel */
    public IventoryJPanel() {
        initComponents();

        try {
            updateTable();
        } catch (SQLException ex) {
            Logger.getLogger(IventoryJPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void updateTable() throws SQLException {
        // TableModel definition
        String[] tableColumnsName = {" UPC "," ItemName ", " StoreId ", " StoreName ", " quantity "};

        DefaultTableModel aModel = (DefaultTableModel) jTable8_invenroy.getModel();
        aModel.setColumnIdentifiers(tableColumnsName);

// the query

         PreparedStatement  ps;
         Connection con = DBAccessSingleton.getInstance().getConnection();
        // ps = con.prepareStatement("select stock.UPC,* from stock stock1, stock_item item, store,store1 ");
          ps = con.prepareStatement("select stock1.UPC, item.name, stock1.storeId, s.name, stock1.quantity "
                  + "from stock stock1, stock_item item,store s  "
                  + "where stock1.UPC = item.UPC AND stock1.storeId = s.storeId ");
         ResultSet rs = ps.executeQuery();

// Loop through the ResultSet and transfer in the Model
        java.sql.ResultSetMetaData rsmd = rs.getMetaData();
        int colNo = rsmd.getColumnCount();
        while (rs.next()) {
            Object[] objects = new Object[colNo];
            // tanks to umit ozkan for the bug fix!
            for (int i = 0; i < colNo; i++) {
                objects[i] = rs.getObject(i + 1);
            }
            aModel.addRow(objects);
        }
        jTable8_invenroy.setModel(aModel);
        rs.close();
        con.close();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane8_inventory = new javax.swing.JScrollPane();
        jTable8_invenroy = new javax.swing.JTable();
        jButton1_InsertStock = new javax.swing.JButton();
        jButton2_edit = new javax.swing.JButton();
        jButton3_deleteRow = new javax.swing.JButton();

        setName("Form"); // NOI18N
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jScrollPane8_inventory.setName("jScrollPane8_inventory"); // NOI18N

        jTable8_invenroy.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "null", "null", "null", "null", "null"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable8_invenroy.setName("jTable8_invenroy"); // NOI18N
        jScrollPane8_inventory.setViewportView(jTable8_invenroy);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(shopaddmin.ShopAddminApp.class).getContext().getResourceMap(IventoryJPanel.class);
        jTable8_invenroy.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTable8_invenroy.columnModel.title0")); // NOI18N
        jTable8_invenroy.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTable8_invenroy.columnModel.title1")); // NOI18N
        jTable8_invenroy.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("jTable8_invenroy.columnModel.title2")); // NOI18N
        jTable8_invenroy.getColumnModel().getColumn(3).setPreferredWidth(25);
        jTable8_invenroy.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("jTable8_invenroy.columnModel.title3")); // NOI18N
        jTable8_invenroy.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("jTable8_invenroy.columnModel.title4")); // NOI18N

        add(jScrollPane8_inventory, new org.netbeans.lib.awtextra.AbsoluteConstraints(62, 69, 744, 407));

        jButton1_InsertStock.setText(resourceMap.getString("jButton1_InsertStock.text")); // NOI18N
        jButton1_InsertStock.setName("jButton1_InsertStock"); // NOI18N
        jButton1_InsertStock.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1_InsertStockActionPerformed(evt);
            }
        });
        add(jButton1_InsertStock, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 500, 96, 50));

        jButton2_edit.setText(resourceMap.getString("jButton2_edit.text")); // NOI18N
        jButton2_edit.setName("jButton2_edit"); // NOI18N
        jButton2_edit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2_editActionPerformed(evt);
            }
        });
        add(jButton2_edit, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 500, 96, 50));

        jButton3_deleteRow.setText(resourceMap.getString("jButton3_deleteRow.text")); // NOI18N
        jButton3_deleteRow.setName("jButton3_deleteRow"); // NOI18N
        jButton3_deleteRow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3_deleteRowActionPerformed(evt);
            }
        });
        add(jButton3_deleteRow, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 500, 115, 50));
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1_InsertStockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1_InsertStockActionPerformed
        // TODO add your handling code here:
         if (AddStockDlg == null) {
            JFrame mainFrame = ShopAddminApp.getApplication().getMainFrame();
            AddStockDlg = new JDialog_AddItemToStore(mainFrame,true);
            AddStockDlg.setLocationRelativeTo(mainFrame);
        }
        ShopAddminApp.getApplication().show(AddStockDlg);
        
         DefaultTableModel aModel = (DefaultTableModel) jTable8_invenroy.getModel();

         while (aModel.getRowCount()>0){
              aModel.removeRow(0);
         }

        try {
            updateTable();
        } catch (SQLException ex) {
            Logger.getLogger(IventoryJPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1_InsertStockActionPerformed

    private void jButton3_deleteRowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3_deleteRowActionPerformed
        // TODO add your handling code here:
        int row = jTable8_invenroy.getSelectedRow();
        if (row >=0){
            try {
                Integer UPC = (Integer) jTable8_invenroy.getValueAt(row, 0);
                Integer stroreId = (Integer) jTable8_invenroy.getValueAt(row, 2);
                DefaultTableModel tModel = (DefaultTableModel) jTable8_invenroy.getModel();
                // remove from table
                tModel.removeRow(row);
                //delete from db
                PreparedStatement ps;
                Connection con = DBAccessSingleton.getInstance().getConnection();
                ps = con.prepareStatement("DELETE FROM shop_db.stock WHERE `UPC` = ? AND `storeId` = ? ");
                ps.setInt(1, UPC);
                ps.setInt(2, stroreId);

                ps.executeUpdate();
                ps.close();
                con.close();

            } catch (SQLException ex) {
                Logger.getLogger(IventoryJPanel.class.getName()).log(Level.SEVERE, null, ex);
            }

        }else {JOptionPane.showConfirmDialog(null,
                        "Please Select a row first", "Please Select a row first",
                        JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE);
        }
    }//GEN-LAST:event_jButton3_deleteRowActionPerformed

    private void jButton2_editActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2_editActionPerformed
        // TODO add your handling code here:
         // TODO add your handling code here:
         if (EditStockDlg == null) {
            JFrame mainFrame = ShopAddminApp.getApplication().getMainFrame();
            EditStockDlg = new EditStockJDialog (mainFrame,true);
            EditStockDlg.setLocationRelativeTo(mainFrame);             
        }
         int row = jTable8_invenroy.getSelectedRow();

            if (row >= 0) {
                Integer UPC = (Integer) jTable8_invenroy.getValueAt(row, 0);
                Integer stroreId = (Integer) jTable8_invenroy.getValueAt(row, 2);
                Integer quantity = (Integer) jTable8_invenroy.getValueAt(row, 4);

//                System.out.println(UPC);
//                System.out.println(stroreId);
//                System.out.println(quantity);

                EditStockDlg.getjTextField1_upc().setText(UPC.toString());
                EditStockDlg.getjTextField2_StoreId().setText(stroreId.toString());
                EditStockDlg.getjTextField3_quantity().setText(quantity.toString());

            } else {
                JOptionPane.showConfirmDialog(null,
                        "Please Select a row first", "Please Select a row first",
                        JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE);
                return;
            }
        ShopAddminApp.getApplication().show(EditStockDlg);

         DefaultTableModel aModel = (DefaultTableModel) jTable8_invenroy.getModel();

         while (aModel.getRowCount()>0){
              aModel.removeRow(0);
         }

        try {
            updateTable();
        } catch (SQLException ex) {
            Logger.getLogger(IventoryJPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton2_editActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1_InsertStock;
    private javax.swing.JButton jButton2_edit;
    private javax.swing.JButton jButton3_deleteRow;
    private javax.swing.JScrollPane jScrollPane8_inventory;
    private javax.swing.JTable jTable8_invenroy;
    // End of variables declaration//GEN-END:variables

    private JDialog_AddItemToStore AddStockDlg;
    private EditStockJDialog EditStockDlg;
}
